# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :jwt_util.py
# @Time      :2022/6/8 0008 20:12
# @Author    :何胜利
from datetime import datetime, timedelta

import jwt
from flask import current_app


# 生成token
def generate_jwt(payload, expiry, secret=None):
    if "expiry" not in payload:
        payload["expiry"] = str(expiry)

    if not secret:
        secret = current_app.config["SECRET_KEY"]

    token = jwt.encode(payload, secret, algorithm="HS256")
    return token


# 验证token
def create_token(token, secret=None):
    if not secret:
        secret = current_app.config["SECRET_KEY"]

    try:
        payload = jwt.decode(token, secret, algorithms="HS256")
        return payload
    except Exception as e:
        print("验证token的错误信息", e)
        return None


def _generate_token(payload, is_refresh=True):

    secret = current_app.config['SECRET_KEY']

    expiry = datetime.utcnow() + timedelta(hours=2)
    token = generate_jwt(payload, expiry, secret)
    if is_refresh:

        expiry = datetime.utcnow() + timedelta(days=15)

        payload.update({"is_refresh": True})
        print('刷新token 的payload```', payload)
        refresh_token = generate_jwt(payload, expiry, secret)
    else:
        refresh_token = None

    return token, refresh_token
